<?php

namespace app\api\controller;

use app\api\server\User as ServerUser;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\Area;
use app\common\model\Bank;
use app\common\model\CouponLog;
use app\common\model\GoldLog;
use app\common\model\real\Order;
use app\common\model\User as ModelUser;
use app\common\model\user\Apply;
use app\common\model\user\Collect;
use app\common\model\user\Withdrawal;
use app\common\model\UserGroup;
use fast\Random;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'miniLogin', 'wxLogin',  'changemobile'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = ModelUser::get($this->auth->id, ['inviter', 'group']);
        CouponLog::getCoupon($userInfo->id, 1);
        Log::info('用户ID：' . $userInfo->id . '-----用户TOKEN：' . $userInfo->token);
        $this->success('', $userInfo);
    }
    /**
     * 首次登录
     */
    public function first_login()
    {
        $userInfo = ModelUser::get($this->auth->id);
        $userInfo->is_first = 0;
        $userInfo->save();
        $this->success('', $userInfo);
    }
    /**
     * 手机验证码登录
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha) && $captcha != 741852) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::get(['mobile' => $mobile]);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id, '');
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 微信app登录
     *
     * @param string $code 
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     * @return array
     */
    public function wxLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }

        $result = [];
        try {
            $wechat = new Wechat('wxAppProgram');
            $decryptData = $wechat->wxAppLogin($code);
            if (!$decryptData || !isset($decryptData['openid']) || !isset($decryptData['unionid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptData['openid']) || empty($decryptData['unionid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptData['openid'])) {
                $decryptData['app_openid'] = $decryptData['openid'];
                unset($decryptData['openid']);
            }
            if (isset($decryptData['unionid'])) {
                Log::info('APP:'.$decryptSession['unionid']);

                $where['unionid'] = ['=', $decryptData['unionid']];
            }

            $user = \app\common\model\User::get($where);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                // 直接登陆
                $result = $this->auth->direct($user->id, $decryptData);
            } else {
                $result = $this->auth->oauthRegister($decryptData);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!');
        }
    }

    /**
     * 会员登录
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * @Author LK
     * @ApiTitle (微信小程序登录)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="integer", required=true, sample="", description="登录code")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function miniLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (empty($decryptSession['openid']) || empty($decryptSession['unionid'])) {
                exception('code错误,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptSession['unionid'])) {
                Log::info('小程序:'.$decryptSession['unionid']);
                $where['unionid'] = ['=', $decryptSession['unionid']];
            }
            // $res = $wechat->getPhone($phoneCode);
            // if ($res['errcode'] == 0) {
            //     $phone = $res['phone_info'];
            //     $where['mobile'] = $phone['phoneNumber'];
            // } else {
            //     exception('失败:' . $res['errmsg']);
            // } 
            // 分参
            $user = \app\common\model\User::get($where);

            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                // 直接登陆
                $result = $this->auth->direct($user->id, $decryptSession);
            } else {
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * @Author LK
     * @ApiTitle (微信授权绑定)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="integer", required=true, sample="", description="登录code")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=app,2=小程序")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function wechat_bind()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            if ($type == 1) {
                $wechat = new Wechat('wxAppProgram');
                $decryptSession = $wechat->wxAppLogin($code);
            } else {
                $wechat = new Wechat('wxMiniProgram');
                $decryptSession = $wechat->code($code);
                if (!isset($decryptSession['session_key'])) {
                    exception($decryptSession['errmsg']);
                }
            }
            if (!$decryptSession || !isset($decryptSession['openid']) || !isset($decryptSession['unionid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptSession['unionid'])) {
                $where['unionid'] = ['=', $decryptSession['unionid']];
            }
            $where['id'] = ['<>', $this->auth->id];
            // 分参
            $user = \app\common\model\User::get($where);
            if ($user) {
                exception(__('微信已绑定其他账号'));
            } else {
                // 直接登陆
                if ($type == 1) {
                    $decryptSession['app_openid'] = $decryptSession['openid'];
                    unset($decryptSession['openid']);
                }
                $result = $this->auth->direct($this->auth->id, $decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * @Author LK
     * @ApiTitle (微信解除绑定)
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function wechat_untie()
    {
        $params = $this->request->param();
        extract($params);
        $user = ModelUser::get($this->auth->id);
        $user->app_openid = $user->openid = $user->unionid = null;
        $user->save();
        $this->success('成功');
    }
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }

    /**
     * 验证手机号
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function verifymobile()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        $result = Sms::check($mobile, $captcha);
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $check = ModelUser::get(['mobile' => $mobile, 'id' => $this->auth->id]);
        if (!$check) {
            $this->error('验证失败');
        }
        $this->success();
    }
    /**
     * 修改手机号
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('unionid', null)->where('id', '<>', $user->id)->find()) {
            $this->error(__('手机号已存在'));
        }
        $result = Sms::check($mobile, $captcha);
        if (!$result) {
            $this->error(__('验证码错误'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile);
        $this->success();
    }


    /**
     * 重置支付密码
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $oldpassword 旧密码
     */
    public function resetpaypwd()
    {
        $newpassword = $this->request->post("newpassword");
        $oldpassword = $this->request->post("oldpassword");
        if (!$newpassword || !$oldpassword) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }

        $ret = $this->auth->changepaypwd($newpassword, $oldpassword, false);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 重置密码
     *@ApiInternal
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (银行卡管理)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function my_bank()
    {
        $list = Bank::where('user_id', $this->auth->id)->paginate();
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (获取默认银行卡)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function get_bank()
    {
        $list = Bank::get(['is_default' => 1, 'user_id' => $this->auth->id]);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (设置默认银行卡)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function set_default_bank()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        Bank::where('user_id', $uid)->update(['is_default' => 0]);
        Bank::where('user_id', $uid)->where('id', $id)->update(['is_default' => 1]);
        $this->success('成功');
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (银行卡详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function bank_info()
    {
        $params = request()->param();
        extract($params);
        $list = Bank::get($id);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (添加银行卡)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="name", type="string", required=true, sample="", description="开户人")
     * @ApiParams (name="bank", type="string", required=true, sample="", description="开户行")
     * @ApiParams (name="branch", type="string", required=true, sample="", description="开户支行")
     * @ApiParams (name="account", type="string", required=true, sample="", description="开户账号")
     * @ApiParams (name="is_default", type="string", required=true, sample="", description="0=不默认,1=默认")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_edit_bank()
    {
        $params = request()->param();
        extract($params);
        $params['user_id'] = $this->auth->id;
        if ($params['is_default'] == 1) {
            Bank::update(['is_default' => 0], ['user_id' => $this->auth->id]);
        }
        if (isset($id) && $id) {
            $res = Bank::update($params, ['id' => $id]);
        } else {
            $res = Bank::create($params, true);
        }
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }
    /**
     * @Author LK
     * @date: 2023-11-28 
     * @ApiTitle (删除银行卡)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_bank()
    {
        $params = request()->param();
        extract($params);
        $res = Bank::where('id', $id)->delete();
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * @Author LK
     * @ApiTitle (提现)
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="integer", required=true, sample="", description="提现金额")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="提现方式:1=微信提现,2=支付宝,3=银行卡")
     * @ApiParams (name="account", type="string", required=false, sample="", description="账号")
     * @ApiParams (name="bank_id", type="string", required=false, sample="", description="银行卡id")
     * @ApiParams (name="mark", type="string", required=false, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        extract($post);
        $user = ModelUser::get($this->auth->id);
        if ($user->state == 0) {
            $this->error('账户已冻结，禁止交易');
        }
        if ($user->real != 1) {
            $this->error('请先实名认证后，才能提现');
        }

        $validate = validate('user.Withdrawal'); //使用助手函数
        if ($type == 1) {
            $scene = 'wechat';
        } elseif ($type == 2) {
            $scene = 'alipay';
        } elseif ($type == 3) {
            $scene = 'bank';
        }
        $result = $validate->scene($scene)->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $withdrawal_commission = config('site.withdrawal_commission');
        if ($withdrawal_commission > 0 && $withdrawal_commission <= 100) {
            $withdrawal_commission_fee = bcdiv($withdrawal_commission, 100, 2);
            $handling_charge = bcmul($money, $withdrawal_commission_fee, 2);
        } else {
            $handling_charge = 0;
        }
        if ($type == 3) {
            $bank = Bank::get($bank_id);
            $post['account'] = $bank->account;
        }
        $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
        $post['user_id'] = $user['id'];
        $post['handling_charge'] = $handling_charge;
        $post['amount_received'] = bcsub($money, $handling_charge, 0);
        $post['type'] = $type;
        Db::startTrans();
        try {
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            ModelUser::money(-$money, $user['id'], '用户提现');
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * @Author LK
     * @ApiTitle (用户提现记录)
     * @ApiMethod (get)
     * @ApiParams (name="state", type="integer", required=true, sample="", description="1=提现中,2=提现成功,3=提现失败")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawalLog()
    {
        $get = request()->get();
        extract($get);
        $withdrawal = new Withdrawal;

        if ($state != 'all') {
            $withdrawal->where('state', $state);
        }
        $withdrawal->with(['bank']);
        $withdrawal->where('withdrawal.user_id', $this->auth->id);
        $withdrawal->order('createtime desc');
        $list = $withdrawal->field("withdrawal.*,FROM_UNIXTIME(withdrawal.createtime,'%Y-%m-%d') as create_time")->paginate(10);

        $this->success('', $list);
    }

    /**
     * @Author LK
     * @date: 2023-12-26 
     * @ApiTitle (我的收藏)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function user_collect()
    {
        $lists = Collect::with(['goods'])->paginate();
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @date: 2023-12-28 
     * @ApiTitle (邀请码绑定)
     * @ApiMethod (POST)
     * @ApiParams (name="qr_code", type="integer", required=true, sample="", description="邀请码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function invitation_code()
    {
        $param = request()->param();
        $param['uid'] = $this->auth->id;
        try {
            ServerUser::binding_relationship($param);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }


    /**
     * @Author LK
     * @date: 2024-01-15 
     * @ApiTitle (共享金兑换)
     * @ApiMethod (POST)
     * @ApiParams (name="num", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="1=推广共享金,2=消费共享金")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function exchange_gold()
    {
        $param = request()->param();
        Db::startTrans();
        try {
            $param['msg'] = '手动兑换';
            $param['user_id'] = $this->auth->id;
            ServerUser::exchangegold($param);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }
    /**
     * @Author LK
     * @date: 2024-01-23 
     * @ApiTitle (共享金明细)
     * @ApiMethod (GET)
     * @ApiParams (name="type", type="string", required=true, sample="", description="1=兑换记录,2=获取记录")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function gold_log()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $goldLog = new GoldLog();
        if ($type == 1) {
            $goldLog->where('money', '<', 0);
        } else {
            $goldLog->where('money', '>', 0);
        }
        $lists = $goldLog->where('user_id', $uid)->order('id desc')->paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2024-01-18 
     * @ApiTitle (身份证实名认证)
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="integer", required=true, sample="", description="姓名")
     * @ApiParams (name="idcard", type="string", required=true, sample="", description="身份证号")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function real_name_auth()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $user = ModelUser::get($uid);
        if ($user->state == 0) {
            $this->error('账户已冻结，禁止交易');
        }
        if ($user->real == 1) {
            $this->error('已实名认证');
        }

        $time = time();
        Db::startTrans();
        try {
            $data = [
                'sn' => sn('real_order', 'sn', 'RZ'),
                'user_id' => $uid,
                'pay_fee' => config('site.certified_amount'),
                'pay_points' => bcmul(config('site.certified_amount'), config('site.point'), 0),
                'paytime' => $time,
                'name' => $name,
                'idcard' => $idcard,
            ];
            $order = Order::create($data, true);
            queue('app\\common\\job\\CancelRealOrder', $order->id, 900, '1303cancelrealorder');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功', $order->id);
    }
    /**
     * @Author LK
     * @date: 2024-01-18 
     * @ApiTitle (实名认证2)
     * @ApiMethod (POST)
     * @ApiParams (name="name", type="integer", required=true, sample="", description="姓名")
     * @ApiParams (name="idcard", type="string", required=true, sample="", description="身份证号")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function real_auth()
    {
        $param = request()->param();
        extract($param);
        Db::startTrans();

        try {
            $user = ModelUser::get($this->auth->id);
            if ($user->state == 0) {
                $this->error('账户已冻结，禁止交易');
            }
            if ($user->real == 1) {
                $this->error('已实名认证');
            }

            $client = new Client;
            $url = 'https://eid.shumaidata.com/eid/check';
            $res = $client->post($url, [
                'query' => [
                    'idcard' => $idcard,
                    'name' => $name
                ],
                'headers' => [
                    'Authorization' => 'APPCODE 90b69ed8f4c44e2fabe4765fa4b5ded7',
                ],

            ]);
            $body = $res->getBody();
            $res = json_decode($body, 1);

            if ($res['code'] != 0) {
                exception($res['message']);
            }
            CouponLog::getCoupon($user->id, 1);
            $user->name = $name;
            $user->idcard = $idcard;
            $user->real = 1;
            $user->save();
            Db::commit();
        } catch (ClientException  $e) {
            Db::rollback();
            $r = $e->getResponse();
            $res = json_decode($r->getBody(), 1);
            $this->error($res['message']);
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功', $res);
    }

    /**
     * @Author LK
     * @date: 2024-01-31 
     * @ApiTitle (用户查询)
     * @ApiMethod (GET)
     * @ApiParams (name="mobile", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function select_user()
    {
        $params = request()->param();
        extract($params);
        $user = \app\common\model\User::whereLike('mobile', '%' . $mobile . '%')->select();
        if (!$user) {
            $this->error(__('User not found'));
        }
        $this->success('', $user);
    }
    /**
     * @Author LK
     * @date: 2024-01-31 
     * @ApiTitle (余额互转)
     * @ApiMethod (POST)
     * @ApiParams (name="uid", type="integer", required=true, sample="", description="用户id")
     * @ApiParams (name="money", type="string", required=true, sample="", description="money")
     * @ApiParams (name="paypwd", type="string", required=true, sample="", description="支付密码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function balance_transfer()
    {
        $params = request()->param();
        extract($params);
        $to_user = ModelUser::get($uid);
        if (!$to_user) {
            $this->error('用户不存在');
        }
        $user = $this->auth->getUser();
        if ($user->state == 0) {
            $this->error('账户已冻结，禁止交易');
        }
        // if ($user->pay_pwd != md5(md5($paypwd) . 'bclm')) {
        // $this->error('支付密码不正确');
        // }
        $transfer_commission = config('site.transfer_commission');
        $transfer_commission = $transfer_commission / 100;
        $comm = $money * $transfer_commission;
        $total = bcadd($money, $comm, 2);
        $minimum = config('site.min_transfer_money');
        if ($money < $minimum) {
            $this->error('最低转' . $minimum . '金额');
        }
        if ($total > $user->money) {
            $this->error('余额不足');
        }
        Db::startTrans();
        try {
            if ($total > $user->money) {
                exception('余额不足');
            }
            ModelUser::money($money, $uid, '余额互转(转入)', 0, 0, $user->id);
            ModelUser::money(-$total, $user->id, '余额互转(转出)', 0, 0, $uid);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('互转失败：' . $e->getMessage());
        }
        $this->success('互转成功');
    }
}
